package com.xthh._function;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

public class HH_CharUtil {
    private static final String TAG = "CharUtil";

    public static int Crc16(byte[] pcrc) {
        if (pcrc == null)
            return 0;

        int crc = 0x00;
        int polynomial = 0x1021;
        for (int index = 0; index < pcrc.length; index++) {
            byte b = pcrc[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;

        return crc;
    }

    public static String MD5(String content) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(content.getBytes("UTF-8"));
            byte[] encryption = md5.digest();// 加密
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    sb.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    sb.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static byte[] StrToByteArray(String str) {
        if (str == null) {
            return null;
        }
        byte[] byteArray = str.getBytes();
        return byteArray;
    }

    // boolean to int
    public static int BToI(Boolean flag) {
        return Boolean.compare(flag, Boolean.TRUE) + 1;
    }

    // boolean to string
    // true to "1"
    public static String BToS(Boolean flag) {
        int i = BToI(flag);
        return Itoa(i);
    }

    // string to boolean
    // "1" to true
    public static boolean SToB(String flag) {
        return flag.equals("1");
    }


    public static String ByteToStr(byte []src){
        if (src == null)
            return null;

        return  new String(src);
    }

    public static String ByteToHexStr(byte[] src) {
        if (src == null || src.length <= 0)
            return "";

        String sLog = "";
        for (int i = 0; i < src.length; i++) {
            sLog += String.format("%02x ", src[i] & 0xFF);
        }

        return sLog;
    }

    public static String ByteToHexStr_(byte[] src) {
        if (src == null || src.length <= 0)
            return "";

        String sLog = "";
        for (int i = 0; i < src.length; i++) {
            sLog += String.format("%02X", src[i] & 0xFF);
        }

        return sLog;
    }
    // BCD 码转换
    public static int XTHH_DectoBCD(String src) {

        if (src == null || src.length() <= 0)
            return -1;

        return Integer.parseInt(src, 16);
    }

    // 判断字符串str是不是完全由type串组成，也就是要str必须是由type的串组成
    // str = 12345
    // type = 01234567890
    public static boolean IsCheckStr(String src, String type) {
        if (src == null || type == null)
            return false;
        if (src.length() <= 0)
            return false;
        if (type.length() <= 0)
            return true;

        byte[] bSrc = StrToByteArray(src);
        byte[] bType = StrToByteArray(type);

        if (bSrc == null || bType == null)
            return false;

        for (int j = 0; j < bSrc.length; j++) {
            boolean bOK = false;
            for (int i = 0; i < bType.length; i++) {
                if (bSrc[j] == bType[i]) {
                    bOK = true;
                }
            }
            if (!bOK) {
                return false;
            }
        }

        return true;
    }

    public static String Itoa(int i) {
        return Integer.toString(i);
    }

    public static int Atoi(String str) {
        try {
            if (str == null || str.length() <= 0)
                return 0;
            return Integer.parseInt(str);
        } catch (Exception e) {
            return 0;
        }
    }

    public static long Atol(String str) {
        if (str == null || str.length() <= 0)
            return 0;
        return Long.parseLong(str);
    }

    public static byte[] StringToByte2(String b, String code) {
        byte[] bID = null;
        try {
            bID = b.getBytes(code);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return bID;
    }

    // 字符串转换成为16进制(无需Unicode编码)
    public static String Str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    // 16进制直接转换成为字符串(无需Unicode解码)
    public static String HexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    // 字符串颠倒顺序
    public static String StrReverse(String s) {
        if (s == null)
            return s;
        if (s.length() <= 1)
            return s;

        StringBuffer sb = new StringBuffer();
        char[] ch = s.toCharArray();
        for (int i = ch.length - 1; i >= 0; i--) {
            sb.append(ch[i]);
        }
        if (sb != null)
            return sb.toString();
        else
            return "";
    }


    // 位操作  获取第几位的值，二进制的 返回的0或1
    public static int GetIntBit(int nValue, int nBitPos) {

        if (nBitPos >= (32)) return -1;

        nValue = nValue & 0xff;

        int x2 = (1 & (nValue >> nBitPos));
        //Logging.i(TAG, "GetIntBit:post=%d,value=%d", nBitPos, x2);
        return x2;
        //return (nValue & (0x1 << nBitPos)); // 这个不对，只能判断出0来

        /*if (value > 4095)// 暂时只用这么多，变大会有问题
            return -1;

        String s = Integer.toBinaryString(value);
        if (s == null)
            return 0;

        s = StrReverse(s);
        if (bitPos < s.length()) {
            char c = s.charAt(bitPos);
            if (c == '1')
                return 1;
            else
                return 0;
        }
        return 0;*/
    }

    // 位操作，设置位的值，返回成功的值
    /*
     * Comments: 把32位整形数第nBitPos位置nNum (bBit为true时置1，否则置0)
     * Param unsigned int nValue: 32位整形数
     * Param unsigned int nBitPos: 置位位数
     * Param bool bBit: 置位数
     * @Return int:  成功则 返回置位后的整形数，否则返回-1
     */
    public static int SetIntBit(int nValue, int nBitPos, boolean bBit) {

        if (nBitPos >= (32)) return -1;

        int newValue;

        if (bBit) {
            newValue = (int) (0x1 << nBitPos);
            nValue |= newValue;
        } else {
            newValue = (int) (~(0x1 << nBitPos));
            nValue &= newValue;
        }

        return nValue;

        /*if (value > 4095) // 暂时只用这么多，变大会有问题
            return -1;
        String s = Integer.toBinaryString(value);
        if (s == null)
            return 0;

        s = StrReverse(s) + "000000000000";  // 要保证它大于12位就行

        if (bitPos > s.length())
            return 0;

        StringBuilder strBuilder = new StringBuilder(s);
        strBuilder.setCharAt(bitPos, bit ? '1' : '0');
        s = strBuilder.toString();

        s = StrReverse(s);

        int x = Integer.parseInt(s, 2); // 2进制转为整数

        return x;*/
    }

    // 比较字符串是否相等，最后真表示是否忽略大小写
    public static boolean Strcmp(String src1, String src2, boolean ignore) {
        if (src1 == null && src2 == null)
            return true;
        if (src1 == null || src2 == null)
            return false;
        if (src1.length() == 0 && src2.length() == 0)
            return true;
        if (ignore) {
            if (src1.equalsIgnoreCase(src2))
                return true;
        } else {
            if (src1.equals(src2))
                return true;

        }
        return false;
    }

    public static byte [] GetMacFormStr2(String mac){
        if (mac == null || mac.length() != 12)
            return null;

        byte []result = new byte[6];

        String s1 = mac.substring(0, 2);
        String s2 = mac.substring(2, 4);
        String s3 = mac.substring(4, 6);
        String s4 = mac.substring(6, 8);
        String s5 = mac.substring(8, 10);
        String s6 = mac.substring(10, 12);

        int v1 = Integer.parseInt(s1, 16);
        int v2 = Integer.parseInt(s2, 16);
        int v3 = Integer.parseInt(s3, 16);
        int v4 = Integer.parseInt(s4, 16);
        int v5 = Integer.parseInt(s5, 16);
        int v6 = Integer.parseInt(s6, 16);

        result[0] = (byte) (v1 & 0xff);
        result[1] = (byte) (v2 & 0xff);
        result[2] = (byte) (v3 & 0xff);
        result[3] = (byte) (v4 & 0xff);
        result[4] = (byte) (v5 & 0xff);
        result[5] = (byte) (v6 & 0xff);



        return result;
    }


    // 根据字符串得到MAC
    // 11223344556600112233445566778899
    // 11 22 33 44 55 66 00 112233445566778899
    public static List<String> GetMacsFormStr(String src) {
        // 只保留字符串和ABCDEFabcdef,再以12长度拆分
        String strFind = "1234567890ABCDEFabcdef";

        String strResult = "";
        for (int i = 0; i < src.length(); i++) {
            String fSrc = src.substring(i, i + 1);
            if (strFind.indexOf(fSrc) != -1) {
                strResult += fSrc;
            }
        }
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < strResult.length() / 12; i++) {
            String fSrc = strResult.substring(i * 12, i * 12 + 12);
            list.add(fSrc);
        }
        return list;
    }

    static public byte[] ListToByte(List<Integer> list) {
        if (list.size() <= 0)
            return null;

        byte[] arrayResult = new byte[list.size()];

        for (int i = 0; i < list.size(); i++) {
            byte it = (byte) list.get(i).intValue();
            arrayResult[i] = it;
        }

        return arrayResult;
    }

    // 31:31:31:31:31:31 转313131313131
    // 31 31 31 31 31 31 转313131313131
    // 31。31。31。31。31。31 转313131313131
    static public String GetMacFormStr(String src) {
        String sResult = "";
        if (src == null || src.length() <= 0)
            return sResult;

        // 强制转大写
        src = src.toUpperCase();

        if (src.indexOf("MAC") == 0){
            src = src.substring(3);
        }


            for (int i = 0; i < src.length(); i++) {
            if (src.charAt(i) == '0' || src.charAt(i) == '1' || src.charAt(i) == '2' || src.charAt(i) == '3' || src.charAt(i) == '4' ||
                    src.charAt(i) == '5' || src.charAt(i) == '6' || src.charAt(i) == '7' || src.charAt(i) == '8' || src.charAt(i) == '9' ||
                    src.charAt(i) == 'a' || src.charAt(i) == 'b' || src.charAt(i) == 'c' || src.charAt(i) == 'd' || src.charAt(i) == 'e' || src.charAt(i) == 'f' ||
                    src.charAt(i) == 'A' || src.charAt(i) == 'B' || src.charAt(i) == 'C' || src.charAt(i) == 'D' || src.charAt(i) == 'E' || src.charAt(i) == 'F') {
                sResult += src.charAt(i);
            }
        }

        return sResult;
    }

    public static String formatHexStringI_10(int[] data) {
        if (data == null || data.length < 1)
            return null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            String hex = HH_CharUtil.Itoa(data[i] & 0xff);
            sb.append(hex);
            sb.append(",");
        }
        return sb.toString().trim();
    }

    public static byte[] ToGBK(String info)
    {
        List<Byte> list = new ArrayList<Byte>();
        for (int i = 0; i < info.length(); i++)
        {
            String s = info.substring(i, i+1);
            byte[] sb = s.getBytes(Charset.forName("GBK"));
            if (sb.length == 1){
                list.add((byte) 0);
                list.add(sb[0]);
            } else if (sb.length == 2) {
                list.add(sb[0]);
                list.add(sb[1]);
            }
        }

        byte result[] = new byte[list.size()];
        for (int i = 0; i < list.size(); i++){
            result[i] = list.get(i);
        }

        return result;
    }
}
